/*
 * @Author: Zhang Yingying
 * @Date: 2020-11-05 10:40:36
 * @LastEditors: Zhang Yingying
 * @LastEditTime: 2020-11-28 15:01:02
 */

import Vue from 'vue'
import loginApi from '@/api/LoginApi'
import {
  getAccessToken,
  removeAccessToken,
  setAccessToken,
} from '@/utils/accessToken'
import { resetRouter } from '@/router'
import { title } from '@/config/settings'

const state = {
  token: getAccessToken(),
  userId: '',
  username: '',
  avatar: '',
}
const getters = {
  token: (state) => state.token,
  userId: (state) => state.userId,
  username: (state) => state.username,
  avatar: (state) => state.avatar,
}
const mutations = {
  setToken(state, accessToken) {
    state.token = accessToken
    setAccessToken(accessToken)
  },
  setUserName(state, username) {
    state.username = username
  },
  setAvatar(state, avatar) {
    state.avatar = avatar
  },
  setUserId(state, userId) {
    state.userId = userId
  },
}
const actions = {
  async login({ commit }, userInfo) {
    let resp = await loginApi.login(userInfo)
    if (resp && resp.data) {
      const { token } = resp.data
      commit('setToken', token)
      const hour = new Date().getHours()
      const thisTime =
        hour < 8
          ? '早上好'
          : hour <= 11
          ? '上午好'
          : hour <= 13
          ? '中午好'
          : hour < 18
          ? '下午好'
          : '晚上好'
      Vue.prototype.$notify({
        message: `欢迎登录${title}`,
        title: `${thisTime}！`,
      })
    }
  },
  async getInfo({ commit }) {
    let resp = await loginApi.getInfo()
    if (resp && resp.data) {
      let { account, avatar, id } = resp.data
      commit('setUserName', account)
      commit('setAvatar', avatar)
      commit('setUserId', id)
    }
  },
  async logout({ dispatch }) {
    await loginApi.logout()
    await dispatch('resetToken')
    await resetRouter()
  },
  resetToken({ commit }) {
    commit('setToken', '')
    removeAccessToken()
  },
}
export default { state, getters, mutations, actions }
